package com.ljkj.cordial.chat.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.ims.IMSClientHelper;
import com.ljkj.cordial.chat.activity.LoginActivity;
import com.ljkj.cordial.chat.activity.SplashActivity;
import com.ljkj.cordial.chat.base.BaseActivity;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.notify.AppBadgerManager;
import com.ljkj.cordial.chat.notify.NotificationUtils;
import com.ljkj.cordial.chat.presenter.ChatMainPresenter;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.nic.view.util.JToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/11/19 21:56
 */
public abstract class AppEventActivity<T extends IView> extends BaseActivity {

    protected final static int EVENT_REG_ON_START = 0;
    protected final static int EVENT_REG_ON_CREATE = 1;

    private T mView;
    private Handler mHandler;
    private boolean isRunAfterOnStartRegisterEventBus = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IMSClientHelper.getInstance().setConnectStatusChangedListener(status -> runOnUiThread(() -> {
            if (IMSClientHelper.CONNECT_STATUS_ING == status) {
                onNettyConnecting();
            } else if (IMSClientHelper.CONNECT_STATUS_SUCC == status) {
                onNettyConnectSuccess();
            } else if (IMSClientHelper.CONNECT_STATUS_FAIL == status) {
                onNettyConnectFailure();
            }
        }));
        if (setupEventBusRegSite() == EVENT_REG_ON_CREATE) {
            registerEventBus();
            afterOnCreateRegisterEventBus();
        }
    }

    protected abstract T bindNettyMessageView();

    protected void afterOnCreateRegisterEventBus() {
    }

    protected boolean afterOnStartRegisterEventBus() {
        return false;
    }

    protected T obtainView() {
        return mView;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (setupEventBusRegSite() == EVENT_REG_ON_START) {
            registerEventBus();
            if (isRunAfterOnStartRegisterEventBus)
                isRunAfterOnStartRegisterEventBus = afterOnStartRegisterEventBus();
        }
    }

    protected void onNettyConnecting() {
    }

    protected void onNettyConnectFailure() {
        dismissNet(isShowDefNetDialog());
        JToast.showShort(this, "连接失败");
    }

    protected void onNettyConnectSuccess() {
    }

    protected int setupEventBusRegSite() {
        return EVENT_REG_ON_START;
    }

    protected boolean useDefaultViewLoading() {
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (setupEventBusRegSite() == EVENT_REG_ON_START) {
            unregisterEventBus();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            unregisterEventBus();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public final void onMessageEvent(MessageEvent event) {
        if (null == event) return;
        if (EventConstants.Event.SERVER_MESSAGE_READER != event.event()) return;
        if (null != mView) {
            if (event.action() != EventConstants.Action.FRIEND_LIST_REGISTERED &&
                    event.action() != EventConstants.Action.FRIEND_LIST_TOURISTS &&
                    event.action() != EventConstants.Action.GROUP_LIST_REGISTERED &&
                    event.action() != EventConstants.Action.GROUP_LIST_TOURISTS &&
                    event.action() != EventConstants.Action.OFF_MESSAGE_SEND_REGIST &&
                    event.action() != EventConstants.Action.OFF_MESSAGE_SEND_TOURIST) {
                mView.onReadResponse(event);
            } else {
                mView.onMessageEventHandle(event);
            }
        }
    }

    private void registerEventBus() {
        EventBus.getDefault().register(this);
        mView = bindNettyMessageView();
        bindViewLoadingController();
    }

    private void unregisterEventBus() {
        EventBus.getDefault().unregister(this);
        mView = null;
    }

    private void bindViewLoadingController() {
        if (null != mView && useDefaultViewLoading()) {
            mView.setViewLoadingController(new IView.ViewLoadingController() {
                @Override
                public void showLoading() {
                    showNet(isShowDefNetDialog());
                }

                @Override
                public void hideLoading() {
                    dismissNet(isShowDefNetDialog());
                }
            });
        }
    }

    protected Handler defaultHandler() {
        if (mHandler == null)
            mHandler = new Handler();
        return mHandler;
    }

    protected void taskDelayed(Runnable r, long delayMillis) {
        defaultHandler().postDelayed(r, delayMillis);
    }

    protected void removeTask(Runnable r) {
        defaultHandler().removeCallbacks(r);
    }

    public void onGlobalLoginOut() {
        ChatApp.getInstance().quitApp(this);
        NotificationUtils.clearNotify(this);
        AppBadgerManager.clean(this);
        DeleteHistoryUtil.getInstance().clear(this, (clearCyc, isClear) -> {
            EventBus.getDefault().post(MessageEvent.createUiRefreshWidthData(EventConstants.Action.ON_DELETE_HISTORY, "-"));
            DbController.getInstance().clear();
            ChatApp.getInstance().remove();
            ChatApp.getInstance().setExitFlag(true);
            ChatApp.getInstance().quitApp();
            dismissNet(isShowDefNetDialog());
            LoginActivity.jumpTo(this, Canstants.STATE_REGISTER_LOGINOUT);
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        });

    }
}
